﻿using AutoMapper;
using B.S.BaseData.Domain;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infratructure.Interfares;
using B.S.BaseData.Read.Api.Application.Command.RoleCommand;
using B.S.BaseData.Read.Api.Dtos;
using MediatR;

namespace B.S.BaseData.Read.Api.Application.CommandHander.RoleHander
{
    public class GetRoleCommandHander : IRequestHandler<GetRoleCommand, ApiPaging<List<GetRoleDto>>>
    {

        private readonly IMapper mapper;
        private readonly IBaseRequsitory<User> userRequsitory;
        private readonly IBaseRequsitory<Role> roleRequsitory;
        private readonly IBaseRequsitory<UserRole> userroleRequsitory;

        public GetRoleCommandHander(IMapper mapper, IBaseRequsitory<User> userRequsitory, IBaseRequsitory<Role> roleRequsitory, IBaseRequsitory<UserRole> userroleRequsitory)
        {
            this.mapper = mapper;
            this.userRequsitory = userRequsitory;
            this.roleRequsitory = roleRequsitory;
            this.userroleRequsitory = userroleRequsitory;
        }

        public Task<ApiPaging<List<GetRoleDto>>> Handle(GetRoleCommand request, CancellationToken cancellationToken)
        {
            ApiPaging<List<GetRoleDto>> paging = new ApiPaging<List<GetRoleDto>>();

            // 拆分 DepartmentId 字符串为整数数组
            var departmentIds = request.DepartmentId
                                       .Split(',')
                                       .Select(int.Parse)
                                       .ToList();

            // 构建查询
            var userQuery = userRequsitory.GetAllAsync();
            var roleQuery = roleRequsitory.GetAllAsync();
            var userrolrQuery = userroleRequsitory.GetAllAsync();

            var linq = from u in userQuery
                       join r in roleQuery on u.RoleId equals r.RoleId
                       where departmentIds.Contains(u.DepartmentId) && r.IsDelete == false
                       select new GetRoleDto
                       {
                           RoleId = r.RoleId,
                           RoleName = r.RoleName,
                           UserId = r.UserId,
                           CreateTime = r.CreateTime,
                           Updateid = r.Updateid,
                           UpdateTime = r.UpdateTime,
                           UserName = u.UserName
                       };

            paging.TotalCount = linq.Count();
            paging.TotalPage = (int)Math.Ceiling(paging.TotalCount * 1.0 / request.PageSize);
            var entity = linq.OrderBy(x => x.RoleId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
            paging.Data = mapper.Map<List<GetRoleDto>>(entity);

            return Task.FromResult(paging);
        }
    }
}
